package com.faxsun.web.resolver;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.View;
import org.thymeleaf.spring4.view.AbstractThymeleafView;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;

public class FaxsunInfoViewResolver extends ThymeleafViewResolver {
	@SuppressWarnings("unused")
	private static final Log LOG = LogFactory.getLog(FaxsunInfoViewResolver.class);

	protected Map<String, String> layoutMap = new HashMap<String, String>();
	protected String fullPageLayout = "views/layout/fullPageLayout";

	@Override
	protected View loadView(final String originalViewName, final Locale locale) throws Exception {
		String viewName = originalViewName;

		String longestPrefix = "";
		
		if(originalViewName.contains("mobile")){
			AbstractThymeleafView view = null;
			view = (AbstractThymeleafView) super.loadView(viewName, locale);
			return view;
		}

		for (Entry<String, String> entry : layoutMap.entrySet()) {
			String viewPrefix = entry.getKey();
			String viewLayout = entry.getValue();

			if (viewPrefix.length() > longestPrefix.length()) {
				if (originalViewName.startsWith(viewPrefix)) {
					longestPrefix = viewPrefix;

					if (!"NONE".equals(viewLayout)) {
						viewName = viewLayout;
					}
				}
			}
		}

		if (longestPrefix.equals("")) {
			viewName = getFullPageLayout();
		}

		AbstractThymeleafView view = null;

		view = (AbstractThymeleafView) super.loadView(viewName, locale);
		view.addStaticVariable("templateName", originalViewName);

		return view;
	}

	public Map<String, String> getLayoutMap() {
		return layoutMap;
	}

	/**
	 * @see #getLayoutMap()
	 * @param layoutMap
	 */
	public void setLayoutMap(Map<String, String> layoutMap) {
		this.layoutMap = layoutMap;
	}

	/**
	 * The default layout to use if there is no specifc entry in the layout map
	 * 
	 * @return the full page layout
	 */
	public String getFullPageLayout() {
		return fullPageLayout;
	}

	/**
	 * @see #getFullPageLayout()
	 * @param fullPageLayout
	 */
	public void setFullPageLayout(String fullPageLayout) {
		this.fullPageLayout = fullPageLayout;
	}

}
